from __future__ import print_function
import hid
import time
import threading

HID_VID = 0x17ef
HID_PID = 0xa080

# 定义一个函数来处理用户输入和发送HID消息
def handle_user_input(h):
    while True:
        user_input = input("> ")
        if user_input.lower() == 'exit':
            break
        try:
            # 将输入的字符串分割并转换为字节
            hex_values = user_input.replace("0x", "").split()
            # 确保每个十六进制值都是成对的
            hex_values = [val + '0' if len(val) == 1 else val for val in hex_values]
            hid_values = bytes.fromhex(' '.join(hex_values))
            h.write(hid_values)
        except ValueError as e:
            print(f"Invalid input: {e}")
            # print("Please enter valid hexadecimal values.")

# enumerate USB devices
for d in hid.enumerate():
    keys = list(d.keys())
    keys.sort()
    for key in keys:
        print("%s : %s" % (key, d[key]))
    print()

# try opening a device, then perform write and read
h = hid.device()
try:
    print("Opening the device")
    h.open(HID_VID, HID_PID)  # TREZOR VendorID/ProductID

    print("Manufacturer: %s" % h.get_manufacturer_string())
    print("Product: %s" % h.get_product_string())
    print("Serial No: %s" % h.get_serial_number_string())

    # enable non-blocking mode
    h.set_nonblocking(1)

    print("==================Read the data==================")
    # 创建一个线程来处理用户输入
    input_thread = threading.Thread(target=handle_user_input, args=(h,))
    input_thread.start()

    while True:
        try:
            d = h.read(64)
            if d:
                # 使用格式化字符串以16进制形式打印每个字节
                hex_string = ' '.join(f'{byte:02x}' for byte in d)
                print(hex_string)
            else:
                # 如果没有数据可读，等待一段时间再次尝试
                time.sleep(1)  # 等待1秒
        except Exception as e:
            # 打印异常信息并退出循环
            print(f"An error occurred: {e}")
            break

    # 等待输入线程结束
    input_thread.join()

    print("Closing the device")
    h.close()

except IOError as ex:
    print(ex)
    print("hid error:")
    print(h.error())
    print("")
    print("You probably don't have the hard-coded device.")
    print("Update the h.open() line in this script with the one")
    print("from the enumeration list output above and try again.")

print("Done")